package cn.virens.web.components.open.wxmp.session;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import cn.virens.web.components.open.session.WxSession;
import cn.virens.web.components.open.session.WxSessionImpl;
import cn.virens.web.components.open.session.WxSessionManager;

/**
 * Spring Session 对象
 * 
 * @author virens
 */
public abstract class WxMpSessionManagerBySpring implements WxSessionManager, InitializingBean {
	public static final String DEFAULT_CACHE_NAME = "weixin-mp-session";

	private String cacheName = DEFAULT_CACHE_NAME;

	private org.springframework.cache.Cache mChache;

	@Autowired
	@Qualifier("springCacheManager")
	private org.springframework.cache.CacheManager mCacheManager;

	protected WxSession getSessionByCache(String openid) {
		return mChache.get(openid, WxSessionImpl.class);
	}

	protected void putSessionByCache(String openid, WxSession session) {
		if (openid == null || session == null) return;

		// 判断session是否已经无效了 & 如果无效要删除
		if (session != null && !session.isExpired()) {//
			this.mChache.put(openid, session);
		} else {
			this.mChache.evict(openid);
		}
	}

	protected WxSession createSession(String openid, WxSession saved) {
		return new WxSessionImpl(saved);
	}

	protected WxSession createSession(String openid) {
		return new WxSessionImpl();
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		this.mChache = mCacheManager.getCache(cacheName);
	}
}
